package jp.heartdokyun.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import jp.heartdokyun.R;
import jp.heartdokyun.listener.GoBackListener;
import jp.heartdokyun.listener.TopBackListener;
import jp.heartdokyun.model.Level;
import jp.heartdokyun.util.Utils;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class GameSuccessActivity extends Activity {

	private SoundPool mSoundPool;
	private HashMap<Integer, Integer> soundPoolMap;
	private MediaPlayer mMediaPlayer;
	Timer timer = null;
	Handler handler = new Handler();
	private boolean clickok = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initSounds();

		setContentView(R.layout.game_success);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		TextView tvTitle = (TextView) findViewById(R.id.tv_game_success_title);
		// tvTitle.setText(getIntent().getStringExtra("CHALLENGE_TYPE"));

		// タイマの設定
		timer = new Timer(true);
		timer.schedule(new TimerTask() {

			public void run() {
				// 表示の更新
				handler.post(new Runnable() {
					public void run() {
						clickok = true;
					}
				});
			}
		}, 5000);

		String Level = getIntent().getStringExtra("LEVEL");
		String Type = getIntent().getStringExtra("CHALLENGE_TYPE_VALUE");

		if (Level.equals("")) {
			Level = "1";
		}
		String Title = getResources().getString(R.string.game_tilte) + " "
				+ getIntent().getStringExtra("CHALLENGE_TYPE") + " Lv." + Level;
		tvTitle.setText(Title);

		String imageId = "circle_" + Type + "_lv" + Level;
		ImageView mIVLevelImg = (ImageView) findViewById(R.id.iv_game_level_img);
		mIVLevelImg.setImageResource(getResources().getIdentifier(imageId,
				"drawable", "jp.heartdokyun"));

		ImageButton btnReChallenge = (ImageButton) findViewById(R.id.btn_re_challenge);
		btnReChallenge.setOnClickListener(new GoBackListener(this));

		ImageButton btnStageSelect = (ImageButton) findViewById(R.id.btn_next_stage);
		ImageButton btnReturnMenu = (ImageButton) findViewById(R.id.btn_return_menu);
		if (Level.equals("5")) {
			btnStageSelect.setVisibility(View.INVISIBLE);
			btnReturnMenu.setVisibility(View.VISIBLE);
		}

		ImageButton ibBack = (ImageButton) findViewById(R.id.ib_return_menu);
		ibBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent itMenu = new Intent(GameSuccessActivity.this,
						MenuActivity.class);
				if (clickok) {
					startActivity(itMenu);
				}
			}
		});
		btnStageSelect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent itNextGame = new Intent(GameSuccessActivity.this,
						GameActivity.class);
				itNextGame.putExtra("CHALLENGE_TYPE", getIntent()
						.getStringExtra("CHALLENGE_TYPE"));

				itNextGame.putExtra("CHALLENGE_TYPE_VALUE", getIntent()
						.getStringExtra("CHALLENGE_TYPE_VALUE"));
				int nextlevel = Integer.parseInt(getIntent().getStringExtra(
						"LEVEL")) + 1;

				itNextGame.putExtra("LEVEL", Integer.toString(nextlevel));
				Utils.addLevel(GameSuccessActivity.this, getIntent()
						.getStringExtra("CHALLENGE_TYPE_VALUE"));
				if (clickok) {
					startActivity(itNextGame);
				}

			}
		});

		btnReturnMenu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent itMenu = new Intent(GameSuccessActivity.this,
						MenuActivity.class);
				if (clickok) {
					startActivity(itMenu);
				}
			}
		});

		// ImageButton ibBack = (ImageButton) findViewById(R.id.ib_game_back);
		// ibBack.setOnClickListener(new GoBackListener(this));
		ImageButton ibo = (ImageButton) findViewById(R.id.ic_o);
		ibo.setOnClickListener(new TopBackListener(this));

		ImageButton btnReward = (ImageButton) findViewById(R.id.btn_reward);
		btnReward.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent itRewardCard = new Intent(GameSuccessActivity.this,
						RewardCardActivity.class);
				itRewardCard.putExtra("CHALLENGE_TYPE", getIntent()
						.getStringExtra("CHALLENGE_TYPE"));
				itRewardCard.putExtra("CHALLENGE_TYPE_VALUE", getIntent()
						.getStringExtra("CHALLENGE_TYPE_VALUE"));
				itRewardCard.putExtra("LEVEL",
						getIntent().getStringExtra("LEVEL"));
				if (clickok) {
					startActivity(itRewardCard);
				}
			}
		});
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				playSound(1);
			}
		}).run();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				playSound(2);
			}
		}).run();
		String type = getIntent().getStringExtra("CHALLENGE_TYPE_VALUE");
		String level = getIntent().getStringExtra("LEVEL");
		Level objLevel = getLevelName(type, level);
		setResultView(objLevel);

		View dokidoki = findViewById(R.id.btn_reward);
		// ScaleAnimation scale = new ScaleAnimation(1,2,1,2,
		// dokidoki.getWidth()/2, dokidoki.getHeight()/2);
		ScaleAnimation scale = new ScaleAnimation(1, (float) 1.5, 1,
				(float) 1.5, Animation.RELATIVE_TO_SELF, (float) 0.5,
				Animation.RELATIVE_TO_SELF, (float) 0.5);
		// anim = new ScaleAnimation(from, to, from, to,
		// Animation.RELATIVE_TO_SELF, (float)0.5, Animation.RELATIVE_TO_SELF,
		// (float)0.5);
		// 0.1sec wait
		scale.setStartOffset(100);
		// 1000msの間で
		scale.setDuration(1000);
		// 1回繰り返す
		scale.setInterpolator(new CycleInterpolator(2));

		// アニメーションスタート
		dokidoki.startAnimation(scale);
	}

	void setResultView(Level lv) {
		ImageView ivLevel = (ImageView) findViewById(R.id.iv_gs_level);
		ivLevel.setImageResource(getResources().getIdentifier(
				"level_" + lv.getLevel(), "drawable", "jp.heartdokyun"));

		ImageView ivTitle = (ImageView) findViewById(R.id.iv_gs_title);
		if (!lv.getTitle().trim().equals("")) {
			ivTitle.setImageResource(getResources().getIdentifier(
					"text_title_" + lv.getType() + "_" + lv.getLevel(),
					"drawable", "jp.heartdokyun"));
		} else {
			ivTitle.setImageResource(getResources().getIdentifier("text_close",
					"drawable", "jp.heartdokyun"));
		}

		int playedTime = getIntent().getIntExtra("PLAYED_TIME", 0);
		String rank = "";
		if (lv.getLevel().equals("1")) {
			if (playedTime < 20000) {
				rank = "A";
			} else if (playedTime < 25000) {
				rank = "B";
			} else if (playedTime < 30000) {
				rank = "C";
			}

		} else if (lv.getLevel().equals("2")) {
			if (playedTime < 21000) {
				rank = "A";
			} else if (playedTime < 26000) {
				rank = "B";
			} else if (playedTime < 30000) {
				rank = "C";
			}
		} else if (lv.getLevel().equals("3")) {
			if (playedTime < 22000) {
				rank = "A";
			} else if (playedTime < 27000) {
				rank = "B";
			} else if (playedTime < 30000) {
				rank = "C";
			}
		} else if (lv.getLevel().equals("4")) {
			if (playedTime < 23000) {
				rank = "A";
			} else if (playedTime < 28000) {
				rank = "B";
			} else if (playedTime < 30000) {
				rank = "C";
			}
		} else if (lv.getLevel().equals("5")) {
			if (playedTime < 25000) {
				rank = "A";
			} else if (playedTime < 28000) {
				rank = "B";
			} else if (playedTime < 30000) {
				rank = "C";
			}
		}
		ImageView ivRank = (ImageView) findViewById(R.id.iv_gs_rank);
		if (rank.equals("A")) {
			ivRank.setImageResource(getResources().getIdentifier("rank_a",
					"drawable", "jp.heartdokyun"));
		} else if (rank.equals("B")) {
			ivRank.setImageResource(getResources().getIdentifier("rank_b",
					"drawable", "jp.heartdokyun"));
		} else if (rank.equals("C")) {
			ivRank.setImageResource(getResources().getIdentifier("rank_c",
					"drawable", "jp.heartdokyun"));
		} else {
			ivRank.setImageResource(getResources().getIdentifier("no_rank",
					"drawable", "jp.heartdokyun"));
		}

		TextView tvTime = (TextView) findViewById(R.id.tv_gs_time);
		try {
			if (lv.getTime().equals("")) {
				tvTime.setText("");
			} else {

				tvTime.setText(getDisplayTime(String
						.valueOf(playedTime)));

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getDisplayTime(String time) {
		int playedTime = Integer.parseInt(time);
		int second = playedTime / 1000;
		int miliSecond = playedTime % 1000;

		return Integer.toString(second) + "\""
				+ Integer.toString(miliSecond).substring(0, 1);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return false;
	}

	@Override
	public void onDestroy() {
		mSoundPool.release();
		if (mMediaPlayer != null)
			mMediaPlayer.release();
		super.onDestroy();
	}

	@Override
	public void onResume() {
		// if (MainActivity.isEnableBGM) {
		// mMediaPlayer.start();
		// } else {
		// if (mMediaPlayer.isPlaying()) {
		// mMediaPlayer.pause();
		// mMediaPlayer.seekTo(0);
		// }
		// }
		if (MainActivity.isEnableBGM) {
			mMediaPlayer = MediaPlayer.create(getApplicationContext(),
					R.raw.other_bgm);
			mMediaPlayer.setLooping(true);
			float volume = Utils.getBGMVolume(getApplicationContext());
			mMediaPlayer.setVolume(volume, volume);
			mMediaPlayer.start();
		}
		super.onResume();
	}

	@Override
	public void onPause() {
		// if (mMediaPlayer.isPlaying()) {
		// mMediaPlayer.pause();
		// mMediaPlayer.seekTo(0);
		// }
		if (mMediaPlayer != null)
			mMediaPlayer.release();
		super.onPause();
	}

	private void initSounds() {
		mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
		soundPoolMap = new HashMap<Integer, Integer>();
		soundPoolMap.put(1,
				mSoundPool.load(getApplicationContext(), R.raw.sugoooi, 1));
		soundPoolMap.put(2, mSoundPool.load(getApplicationContext(),
				R.raw.reberukuriadane, 1));

		// soundPoolMap.put(2,
		// mSoundPool.load(getApplicationContext(), R.raw.loop_33, 1));
	}

	public void playSound(int sound) {
		float volume = Utils.getVoiceVolume(getApplicationContext());
		mSoundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);
	}

	public Level getLevelName(String type, String level) {
		ArrayList<Level> listLevel = Utils.getListLevelFromType(type);
		// String levelName = "";
		Level objLevel = new Level();
		for (int i = 0; i < listLevel.size(); i++) {
			if (listLevel.get(i).getLevel().equals(level)) {
				objLevel = listLevel.get(i);
			}
		}
		return objLevel;
	}

}